package qr;

import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;

import javax.imageio.ImageIO;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;

public class QRGenerator {

    public static String read(Path path) throws IOException, NotFoundException {

        LuminanceSource source = new BufferedImageLuminanceSource(ImageIO.read(Files.newInputStream(path)));

        BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));

        return new MultiFormatReader().decode(bitmap, DecodeHints.instance).getText();
    }

    public static void write(Path path, String content, int width, int height) throws WriterException, IOException {

        BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, EncodeHints.instance);

        MatrixToImageWriter.writeToPath(bitMatrix, "png", path);
    }

    private static class EncodeHints extends HashMap<EncodeHintType, Object> {

        private static final Map<EncodeHintType, Object> instance = new EncodeHints();

        private EncodeHints() { this.put(EncodeHintType.CHARACTER_SET, "UTF-8"); }
    }

    private static class DecodeHints extends HashMap<DecodeHintType, Object> {

        private static final Map<DecodeHintType, Object> instance = new DecodeHints();

        private DecodeHints() { this.put(DecodeHintType.CHARACTER_SET, "UTF-8"); }
    }

    public static void main(String[] args) throws IOException, WriterException, NotFoundException {

        Path target = FileSystems.getDefault().getPath("D://", "qecode.png");

        QRGenerator.write(target, "This is a QR image!", 100, 100);

        System.out.println(QRGenerator.read(target));
    }
}

